#include <QByteArray>
#include <QStringList>
#include <QFileInfo>
#include <QFile>
#include "EnvStrings.h"
#include "Directory.h"
#include "Tricks.h"
#include "Logger.h"
#include "File.h"


Directory::Directory(const DirectorySettings& settings)
: _settings(settings)
, _dir(settings.path)
{}

bool Directory::MakeActive()
{
    disconnect(&_watcher, 0, this, 0);
    
    if (_settings.active)
    {
        _watcher.addPath(_dir.absolutePath());
        connect(&_watcher, SIGNAL(directoryChanged(const QString&)), this, SLOT(OnNewFile()));
    }

    return true;
}

bool Directory::Open()
{
    return (_dir.exists() || _settings.createIfDontExist && _dir.mkpath(_dir.absolutePath())) && MakeActive();
}

bool Directory::IsOpened()
{
    return _dir.exists() && MakeActive();
}

void Directory::Reset()
{}

void Directory::Close()
{}

unsigned Directory::DataAvailable()
{
    return 0;
}

QString Directory::LastError()
{
    return _lastError;
}

QString Directory::Info()
{
    return _dir.absolutePath();
}

QByteArray Directory::Receive(unsigned size)
{
    QFile file(_latestAffected);
    emit keyValueSignal(LatestRead, _latestAffected);
    return file.open(QIODevice::ReadOnly) ? file.readAll() : (logger.addn("Can't read file " + _latestAffected + ". Possible error: " + FileErrorString(file.error())), QByteArray());
}

unsigned Directory::Send(const QByteArray& data)
{
    QFile file(_latestAffected = _dir.filePath((_settings.isNamingArbitrary ? UniqName() : QString("%1").arg(_fileIndex++)) + "." + _settings.extension));
    emit keyValueSignal(LatestSaved, _latestAffected);  
    return file.open(QIODevice::WriteOnly) ? ForceWrite(&file, data) : logger.addn("Can't save file " + _latestAffected + ". Possible error: " + FileErrorString(file.error())), 0;
}

void Directory::OnNewFile()
{
    QFileInfoList affectedFiles = _dir.entryInfoList(QStringList() << _settings.filemask, QDir::Files, QDir::Time);
    
    if (!affectedFiles.isEmpty())
    {
        _latestAffected = affectedFiles.first().absoluteFilePath();
        HasData();
        if (_settings.autodel) QFile(_latestAffected).remove();
    }
}
